<%@ page pageEncoding="UTF-8"%>
<%@ include file="import.jsp"%>
<%@ page import="net.sourceforge.pinyin4j.PinyinHelper"%>
<%@ page import="net.sourceforge.pinyin4j.format.*"%>
<%@ page import="net.sourceforge.pinyin4j.format.exception.*"%>
<%!
	//将汉字转换为全拼
	public String getPinYin(String src) {
		char[] ch = null;
		ch = src.toCharArray();
		String[] str = new String[ch.length];
		HanyuPinyinOutputFormat output = new HanyuPinyinOutputFormat();	
		output.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		output.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		output.setVCharType(HanyuPinyinVCharType.WITH_V);
		String pinYin = "";
		int len = ch.length;
		try {
			for (int i = 0; i < len; i++) {
				// 判断是否为汉字字符
				if (java.lang.Character.toString(ch[i]).matches("[\\u4E00-\\u9FA5]+")) {
					str = PinyinHelper.toHanyuPinyinStringArray(ch[i], output);
					pinYin += str[0];
				} else
					pinYin += java.lang.Character.toString(ch[i]);
			}
			return pinYin;
		} catch (BadHanyuPinyinOutputFormatCombination e1) {
			e1.printStackTrace();
		}
		return pinYin;
	}
	
	// 统计党员信息
	public Long count(Integer partyId, Integer hospital) {
		List<Long> list = QBuilder.db("basedb").queryHql("select count(id) from PartyRelationShip where hospital = " + hospital + " and status = " + STATUS_ENABLE + " and partyId = " + partyId);
		return list.get(0);
	}
	
	// 查询党支部信息
	public Message queryParties(Integer hospital, Integer partyId) {
		List list = QBuilder.db("basedb").queryHql("select new map (p.id as party_id, p.name as party_name, p.branchName as branch_name, count(ps.id) as count) from Party as p, PartyRelationShip as ps where p.hospital = " + hospital + " and p.status = " + STATUS_ENABLE + " and p.id != " + partyId + " and ps.hospital = " + hospital + " and ps.status = " + STATUS_ENABLE + " and p.id = ps.partyId group by ps.partyId");		
		String ids = partyId + "";
		for (int i = 0; i < list.size(); i++) {
			Map p = (Map)list.get(i);
			ids += ("," + Tools.getInt(p.get("party_id") + "", -1));
		}
		List emptyList = QBuilder.db("basedb").queryHql("select new map (p.id as party_id, p.name as party_name, p.branchName as branch_name,  0 as count) from Party as p where p.hospital = " + hospital + " and p.status = " + STATUS_ENABLE + " and p.id not in(" + ids + ")");
		list.addAll(emptyList);
		if (list.size() == 0) {
          return new Message(30041, "暂无数据");
        }
		Map<String, List<Map>> map = new HashMap<String, List<Map>>();
		for (int i = 0; i < list.size(); i++) {
			Map p = (Map)list.get(i);
			if ((p.get("party_name") + "").contains("管理员"))
				continue;
			String branchName = p.remove("branch_name") + "";
			List parties = map.get(branchName);
			if (parties == null) {
				parties = new ArrayList();
				map.put(branchName, parties);
			}
			parties.add(p);
		}
		Set<Entry<String, List<Map>>> entries = map.entrySet();
		List result = new ArrayList();
		for (Entry<String, List<Map>> entry : entries) {
			String key = entry.getKey();
			List<Map> value = entry.getValue();
			Map m = new HashMap();
			m.put("branch_name", key);
			m.put("parties", value);
			result.add(m);
		}
		Message msg = new Message();
		msg.put("list", result);
		return msg;
	}
	
	// 根据院区查党支部信息
	public Message queryPartiesByBranch(Integer hospital, Integer branch) {
		Message msg = new Message();
		String hql = "";
		if (branch != 0) {
			hql = " and p.branch = " + branch;
		}
		List<Map> partyList = QBuilder.db("basedb").queryHql("select new map(p.id as party_id, p.name as party_name, p.branchName as branch_name, p.branch as branch, count(ps.id) as count) from Party p, PartyRelationShip ps where p.hospital = " + hospital + " and p.status = " + STATUS_ENABLE + " and ps.hospital = " + hospital + " and ps.status=" + STATUS_ENABLE + " and p.id = ps.partyId " + hql + " group by p.id");
		StringBuilder ids = new StringBuilder("-99");
		for (int i = 0, length = partyList.size(); i < partyList.size(); i++) {
			ids.append(",");
			ids.append(partyList.get(i).get("party_id"));
		}
		List<Map> emptyList = QBuilder.db("basedb").queryHql("select new map(p.id as party_id, p.name as party_name, p.branchName as branch_name, p.branch as branch, 0 as count) from Party p where p.hospital = " + hospital + " and p.status = " + STATUS_ENABLE + " and p.id not in (" + ids.toString() + ")" + hql);
		partyList.addAll(emptyList);
		if (partyList.isEmpty()) {
			msg.setErrcodeAndErrmsg(30041, "无相关数据");
			return msg;
		}
		Collections.sort(partyList, new Comparator<Map>(){
			public int compare(Map m1, Map m2) {
				return Tools.getDesc(m1.get("branch")).compareTo(Tools.getDesc(m2.get("branch")));
			}
		});
		List list = new ArrayList();
		for (Map partyMap:partyList) {
			if (((String)partyMap.get("party_name")).contains("管理员")) {
				continue;
			}
			list.add(partyMap);
		}
		msg.put("list", list);
		return msg;
	}
	
    // 提出转移申请
    public Message apply(Migrate migrate) {
        Message msg = new Message();
        Integer id = createItem(migrate);
        if (id == null) {
          return new Message(30090, "操作失败");
        }
        msg.put("id", id);
        return msg;
    }

    // 根据状态返回信息
    public String stateInfo(Migrate migrate) {
      Integer exitState = migrate.getOutState();
      Integer enterState = migrate.getInState();
      String msg = "暂无信息";
      if (exitState == 0) {
        msg = "等待批准转出";
      } else if (exitState == 1) {
        msg = "拒绝转出";
      } else if (exitState == 2) {
        if (enterState == 0) {
          msg = "等待批准转入";
        } else if (enterState == 1) {
          msg = "拒绝转入";
        } else {
          msg = "批准转入";
        }
      }
      return msg;
    }
	
	// 根据状态返回信息
    public Integer state(Migrate migrate) {
      Integer exitState = migrate.getOutState();
      Integer enterState = migrate.getInState();
      Integer state = 0;
      if (exitState == 0 || exitState == 1) {
        state = exitState;
      } else if (exitState == 2) {
        state = enterState;
      }
      return state;
    }

    // 转移关系信息
    public List<Map<String, Object>> setMigrateInfo(List<Party> partys, List<Migrate> list, List<UserProfile> userProfiles, List<User> users) {
      List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
      for (int i = 0; i < list.size(); i++) {
        Migrate m = list.get(i);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", m.getId());   // 记录id
        map.put("uid", m.getUid());  // 申请人id
        map.put("original", m.getOriginal()); // 原支部id
        map.put("dest", m.getDest());  // 要转移支部
        map.put("state_info", stateInfo(m));   // 当前状态
		map.put("state", state(m));   // 当前状态码
        map.put("date", DateUtil.formatDate(new Date(m.getcTime())));    // 提出申请时间
        map.put("exit_date", DateUtil.formatDate(m.getOutTime()));  // 支部书记处理时间
        map.put("enter_date", DateUtil.formatDate(m.getInTime()));  // 支部书记处理时间
        map.put("exit_name", m.getOutName());  // 批准离开支部书记姓名
        map.put("enter_name", m.getInName());  // 批准进入支部书记姓名
        map.put("reason", m.getReason());  // 申请离开原因
        map.put("exit_comment", m.getOutComment());  // 评语
        map.put("enter_comment", m.getInComment());  // 寄语
        for (int j = 0; partys != null && j < partys.size(); j++) {
          Party p = partys.get(j);
          if (p.getId().equals(m.getOriginal())) { // 原支部名称
            map.put("exit_name", p.getName());
          } else if (p.getId().equals(m.getDest())) {  // 要进入支部名称
            map.put("enter_name", p.getName());
          }
        }
		 for (int j = 0; users != null && j < users.size(); j++) {  // 获取转移人姓名
          User user = users.get(j);
          if (user.getId().equals(m.getUid())) {
            map.put("name", user.getName());
          }
        }
        for (int j = 0; userProfiles != null && j < userProfiles.size(); j++) {  // 获取转移人姓名
          UserProfile userProfile = userProfiles.get(j);
          if (userProfile.getUid().equals(m.getUid())) {
            map.put("name", Tools.getDesc(userProfile.getName() + "", ""));
            map.put("gender", Tools.getDesc(userProfile.getGender() + "", ""));
            map.put("card_number", Tools.getDesc(userProfile.getCardType() + "", ""));
            map.put("age", Tools.getDesc(userProfile.getAge() + "", ""));
            map.put("phone", Tools.getDesc(userProfile.getPhone() + "", ""));
          }
        }
        result.add(map);
      }
      return result;
    }

    // 查看自己申请
    public Message querySelf(Migrate migrate) {
        Message msg = new Message();
        List<Migrate> list = QBuilder.db("basedb").queryHql("from Migrate where hospital = " + migrate.getHospital() + " and status = " + STATUS_ENABLE + " and uid = " + migrate.getUid() + " order by id desc");
        if (list.size() == 0) {
          return new Message(30041, "暂无数据");
        }
        String ids = "-9999";
        for (int i = 0; i < list.size(); i++) {
          Migrate m = list.get(i);
          Integer org = m.getOriginal();
          Integer dest = m.getDest();
          ids += "," + org + "," + dest;
        }
        List<Party> partys = QBuilder.db("basedb").queryHql("from Party where hospital = " + migrate.getHospital() + " and status = " + STATUS_ENABLE + " and id in("+ ids +")");
        msg.put("list", setMigrateInfo(partys, list, null, null));
        return msg;
    }

    // 书记查看申请记录
    public Message queryApply(Migrate migrate) {
        Message msg = new Message();
        // 提出申请列表
        List<Migrate> exitList = QBuilder.db("basedb").queryHql("from Migrate where hospital = " + migrate.getHospital() + " and status = " + STATUS_ENABLE + " and original = " + migrate.getOriginal() + " and outState = 0 order by cTime desc");
        // 等待批准进入列表
        List<Migrate> enterList = QBuilder.db("basedb").queryHql("from Migrate where hospital = " + migrate.getHospital() + " and status = " + STATUS_ENABLE + " and dest = " + migrate.getOriginal() + " and outState = 2 and inState = 0 order by cTime desc");
        String ids = "-9999";
        for (int i = 0; i < exitList.size(); i++) {
          Migrate m = exitList.get(i);
          Integer org = m.getOriginal();
          Integer dest = m.getDest();
          ids += "," + org + "," + dest;
        }
        for (int i = 0; i < enterList.size(); i++) {
          Migrate m = enterList.get(i);
          Integer org = m.getOriginal();
          Integer dest = m.getDest();
          ids += "," + org + "," + dest;
        }
        List<Party> partys = QBuilder.db("basedb").queryHql("from Party where hospital = " + migrate.getHospital() + " and status = " + STATUS_ENABLE + " and id in("+ ids +")");
        String uids = "-9999";
        for (int i = 0; i < exitList.size(); i++) {
          Migrate m = exitList.get(i);
          Integer uid = m.getUid();
          uids += "," + uid;
        }
        for (int i = 0; i < enterList.size(); i++) {
          Migrate m = enterList.get(i);
          Integer uid = m.getUid();
          uids += "," + uid;
        }
        List<UserProfile> userProfiles = QBuilder.db("basedb").queryHql("from UserProfile where hospital = " + migrate.getHospital() + " and status = " + STATUS_ENABLE + " and self = 0 and uid in("+ uids +")");
		List<User> users = QBuilder.db("basedb").queryHql("from User where hospital = " + migrate.getHospital() + " and status = " + STATUS_ENABLE + " and id in("+ uids +")");
        msg.put("exit_list", setMigrateInfo(partys, exitList, userProfiles, users));
        msg.put("enter_list", setMigrateInfo(partys, enterList, userProfiles, users));
        return msg;
    }

    // 批准或拒绝
    public Message approve(Map<String, String> parameters, Integer uid, boolean isExit) {
      Message msg = new Message();
      int state = Tools.getInt(parameters.get("state"), 0); // 状态
      String comment = Tools.getDesc(parameters.get("comment"), ""); //评语
	  String name = Tools.getDesc(parameters.get("name"), "");  // 批准人姓名
	  List<User> users = QBuilder.db("basedb").queryHql("from User where hospital = " + parameters.get("hospital") + " and status = " + STATUS_ENABLE + " and id = " + uid);
	  if (users.size() > 0) {
		  name = users.get(0).getName();
	  }
      if (state == 0 || uid == 0 || "".equals(name)) {
        return new Message(30041, "参数错误");
      }
      List<Migrate> list =  QBuilder.db("basedb").queryHql("from Migrate where hospital = " + parameters.get("hospital") + " and status = " + STATUS_ENABLE + " and id = " + parameters.get("id"));
      if (list.size() == 0) {
        return new Message(30041, "获取信息失败");
      }
      Migrate m = list.get(0);
	  Integer over = 0;
      boolean changed = false;
	  if (state == 1)
		  over = 1;
      if (isExit) { // 批准离开
        m.setOutState(state);
        m.setOutUid(uid);
        m.setOutName(name);
        m.setOutComment(comment);
        m.setOutTime(new Date());
      } else {
        m.setInState(state);
        m.setInUid(uid);
        m.setInName(name);
        m.setInComment(comment);
        m.setInTime(new Date());
        if (state == 2) {
		  over = 1;
          changed = true;
		}
      }
	  m.setOver(over);
      DBTools.db("basedb").modItem(m, m.getId());
      if (changed) { // 已同意迁入
        Integer dest = m.getDest();
        Integer original = m.getOriginal();
        List<PartyRelationShip> prses = QBuilder.db("basedb").queryHql("from PartyRelationShip where uid = " + m.getUid() +" and partyId = " + original + " and status = " + STATUS_ENABLE);
        if (prses.size() > 0) {
          PartyRelationShip prs = prses.get(0);
          prs.setStatus(STATUS_DISABLE);
          // 先删除原先的党员关系
          DBTools.db("basedb").modItem(prs, prs.getId());
        }
        PartyRelationShip prs = new PartyRelationShip();
        prs.setUid(m.getUid());
		prs.setHospital(m.getHospital());
        prs.setPartyId(dest);
        // 重新创建党员关系
        Integer pid = (Integer)DBTools.db("basedb").addItem(prs);
      }
      return msg;
    }
	
	// 查询该支部下的所有党员
	public Message member(Party party) {
		Message msg = new Message();
		List<Party> list = QBuilder.db("basedb").queryHql("from Party where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and id = " + party.getId());
		if (list.size() == 0) {
			return new Message(30041, "暂无数据");
		}
		party = list.get(0);
		String name = party.getName();
		List<Map> uids = QBuilder.db("basedb").queryHql("select new map(uid as uid, level as level) from PartyRelationShip where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and partyId = " + party.getId());
		String uid = "-999999";
		for (int i = 0; i < uids.size(); i++) {
			uid += "," + Tools.getDesc(uids.get(i).get("uid"), "-1");
		}
		List<User> users = QBuilder.db("basedb").queryHql("from User where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and id in(" + uid + ")");
		List<UserProfile> userProfiles = QBuilder.db("basedb").queryHql("from UserProfile where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and self = 0 and uid in ("+ uid +")");
		List<Map> scoreList = QBuilder.db("basedb").queryHql("from user_score where hospital =" + party.getHospital() + " and status = " + STATUS_ENABLE+ " and uid in (" + uid + ")");
		List<Map> applyList = QBuilder.db("basedb").queryHql("from score_apply where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and apply_uid in (" + uid + ") and is_pass = 1 and is_check = 1");
		List<Map> members = new ArrayList<Map>();
		List normalList = new ArrayList();
		for (int i = 0; i < users.size(); i++) {
			Map map = new HashMap();
			map.put("uid", users.get(i).getId());
			map.put("name", users.get(i).getName());
			map.put("avatar", users.get(i).getAvatar() == null ? "" : users.get(i).getAvatar());
			map.put("phone", "");
			map.put("gender", "");
			map.put("card_number", "");
			map.put("party_name", name);
			map.put("title", users.get(i).getTitle());
			for (int j = 0; j < userProfiles.size(); j++) {
				if (users.get(i).getId().equals(userProfiles.get(j).getUid())) {
					map.put("phone", userProfiles.get(j).getPhone());
					map.put("card_number", userProfiles.get(j).getCardNumber());
					map.put("gender", userProfiles.get(j).getGender());
				}
			}
			for (int k = 0; k < uids.size(); k++) {
				if ((users.get(i).getId() + "").equals(Tools.getDesc(uids.get(k).get("uid"), "-1"))) {
					map.put("level", Tools.getInt(uids.get(k).get("level") + "", 1));
				}
			}
			int score = 100;
			for (Map scoreMap:scoreList) {
				if (users.get(i).getId().equals(Tools.getInt(scoreMap.get("uid") + ""))) {
					score = Tools.getInt(scoreMap.get("score") + "");
					break;
				}
			}
			for (Map applyMap:applyList) {
				if (users.get(i).getId().equals(Tools.getInt(applyMap.get("apply_uid") + ""))) {
					score += Tools.getInt(applyMap.get("score") + "");
				}
			}
			map.put("score", score + "");
			if("支部书记".equals(map.get("title"))){
				map.put("flag", 0);
				members.add(map);
			} else if("组织委员".equals(map.get("title"))){
				map.put("flag", 1);
				members.add(map);
			} else if("宣传委员".equals(map.get("title"))){
				map.put("flag", 2);
				members.add(map);
			}else{
				normalList.add(map);
			}
		}
		Collections.sort(members, new Comparator() {

			@Override
			public int compare(Object o1, Object o2) {
				return ((Integer)((Map)o1).get("flag")).compareTo((Integer)(((Map)o2).get("flag")));
			}
		});
		Collections.sort(normalList, new Comparator() {

			@Override
			public int compare(Object o1, Object o2) {
				return getPinYin((((Map)o1).get("name") + "")).compareTo(getPinYin((((Map)o2).get("name") + "")));
			}
		});
		members.addAll(normalList);
		msg.put("members", members);
		msg.put("count", members.size());
		return msg;
	}
	
	// 查询书记
	public Message secretary(Party party) {
		Message msg = new Message();
		
		int count = 0;
		
		String hql = "";
		if(!"0".equals(party.getBranch())){
			hql = hql + " and branch = '" + party.getBranch() + "'";
		}
		
		List<Party> list = QBuilder.db("basedb").queryHql("from Party where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + hql);
		if (list.size() == 0) {
			return new Message(30041, "暂无数据");
		}
		List<Map> uids = QBuilder.db("basedb").queryHql("select new map(uid as uid, level as level, partyId as party_id) from PartyRelationShip where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and level = 2");
		String uides = "-999999";
		for (int i = 0; i < uids.size(); i++) {
			int number = Tools.getInt(uids.get(i).get("uid") + "", -1);
			uides += "," + number;
		}
		List<User> users = QBuilder.db("basedb").queryHql("from User where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and id in(" + uides + ")");
		List<UserProfile> userProfiles = QBuilder.db("basedb").queryHql("from UserProfile where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and self = 0 and uid in ("+ uides +")");
		List<Map> scoreList = QBuilder.db("basedb").queryHql("from user_score where hospital =" + party.getHospital() + " and status = " + STATUS_ENABLE+ " and uid in (" + uides + ")");
		List<Map> applyList = QBuilder.db("basedb").queryHql("from score_apply where hospital = " + party.getHospital() + " and status = " + STATUS_ENABLE + " and apply_uid in (" + uides + ") and is_pass = 1 and is_check = 1");
		List members = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Party p = list.get(i);
			if ("管理员".equals(p.getName()) || "超级管理员".equals(p.getName())) {
				continue;
			}
			Map map = new HashMap();
			map.put("party_name", p.getName());
			map.put("level", 2);
			map.put("party_id", p.getId());
			map.put("branch", p.getBranch());
			map.put("branch_name", p.getBranchName());
			int uid = -1;
			for (int j = 0; j < uids.size(); j++) {
				int partyId = Tools.getInt(uids.get(j).get("party_id") + "", -9999);
				if (partyId == p.getId()) {
					uid = Tools.getInt(uids.get(j).get("uid") + "", -1);
					count++;
				}
			}
			map.put("uid", uid);
			for (int k = 0; k < users.size(); k++) {
				if (uid == users.get(k).getId()) {
					map.put("name", users.get(k).getName());
					map.put("avatar", users.get(k).getAvatar() == null ? "" : users.get(k).getAvatar());
					map.put("phone", "");
					map.put("gender", "");
					map.put("card_number", "");
				}
			}
			for (int m = 0; m < userProfiles.size(); m++) {
				if (uid == userProfiles.get(m).getUid()) {
					map.put("phone", userProfiles.get(m).getPhone());
					map.put("card_number", userProfiles.get(m).getCardNumber());
					map.put("gender", userProfiles.get(m).getGender());
				}
			}
			int score = 100;
			for (Map scoreMap:scoreList) {
				if (map.get("uid").equals(Tools.getInt(scoreMap.get("uid") + ""))) {
					score = Tools.getInt(scoreMap.get("score") + "");
					break;
				}
			}
			for (Map applyMap:applyList) {
				if (map.get("uid").equals(Tools.getInt(applyMap.get("apply_uid") + ""))) {
					score += Tools.getInt(applyMap.get("score") + "");
				}
			}
			map.put("score", score + "");
			members.add(map);
		}
		Collections.sort(members, new Comparator() {

			@Override
			public int compare(Object o1, Object o2) {
				return getPinYin((((Map)o1).get("name") + "")).compareTo(getPinYin((((Map)o2).get("name") + "")));
			}
		});
		msg.put("members", members);
		msg.put("count", count);
		return msg;
	}
%>
